iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 18
0

第17章 玩玩 LINEBOT

用Flask 開發的LINE BOT,有非常著名的卡米狗

1.LINEBOT 回聲機器人

利用LINE 官方提供的的SDK

2.使用的套件

需要
requirements.txt
說明:佈署時會依照這個文件內容,在伺服端自動進行套件的安裝,讓我們的程式順利運作。

製作方式
pip freeze >requirements.txt

flask python web framework kit
pip install flask
pip install line-bot-sdk
建立requirements.txt 在專案的根目錄
內容
line-bot-sdk
flask
requests

3.

# -*- coding: utf-8 -*-

#  Licensed under the Apache License, Version 2.0 (the "License"); you may
#  not use this file except in compliance with the License. You may obtain
#  a copy of the License at
#
#       https://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#  License for the specific language governing permissions and limitations
#  under the License.

from __future__ import unicode_literals

import os
import sys
from argparse import ArgumentParser

from flask import Flask, request, abort
from linebot import (
    LineBotApi, WebhookParser
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)

app = Flask(__name__)

# get channel_secret and channel_access_token from your environment variable
channel_secret = os.getenv('LINE_CHANNEL_SECRET', None)
channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)
if channel_secret is None:
    print('Specify LINE_CHANNEL_SECRET as environment variable.')
    sys.exit(1)
if channel_access_token is None:
    print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')
    sys.exit(1)

line_bot_api = LineBotApi(channel_access_token)# 來自LINE開發者網站提供的TOKEN
parser = WebhookParser(channel_secret)#來自開發者網站提供的通道銷

"""
@app python 的修飾器,可以視為參考點
.route("/callback/",methods=['POST'])透過flask 框架註冊轉址路由的網路路由位置
在網址實際會變成 http://127.0.0.1/callback/
"""
@app.route("/callback", methods=['POST'])
def callback():
    signature = request.headers['X-Line-Signature']#line的數位簽署 不能省略

    # get request body as text #接收來自於使用者傳送的訊息
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # parse webhook body# 處理json 格式的資料
    try:
        events = parser.parse(body, signature)
    except InvalidSignatureError:
        abort(400)

    # if event is MessageEvent and message is TextMessage, then echo text
    for event in events:#Line 機器人回應的方式
        if not isinstance(event, MessageEvent):
            continue
        if not isinstance(event.message, TextMessage):
            continue
        #line api 直接回傳來自event.message.text的文字
        可以直接替換成"你好..等等招呼語"
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text=event.message.text)
        )

    return 'OK' 回覆傳輸狀況 OK == 200

# App 的執行區段設定

if __name__ == "__main__":
    arg_parser = ArgumentParser(
        usage='Usage: python ' + __file__ + ' [--port <port>] [--help]'
    )
    arg_parser.add_argument('-p', '--port', type=int, default=8000, help='port')
    arg_parser.add_argument('-d', '--debug', default=False, help='debug')
    options = arg_parser.parse_args()

    app.run(debug=options.debug, port=options.port)

4. 資料來源

LINE SDK GITHUB

Day 18.... 前面的幾天的BUG還解不掉啊⋯⋯


上一篇
{Day17}佈署!!AZURE!!
下一篇
{Day 19}Line! 告訴我現在幾點?
系列文
第12 屆IT鐵人賽 -Python新手玩玩Web應用30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言